package PersistenciaDAOs;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import logica.Chorro;
import logica.ConexionBD;
import exceptions.PersistenciaException;
import SQLQrys.QrysChorro;


public class DAOChorro {
	
		private ConexionBD DBC;
		
		public DAOChorro(){
			
		}
		
		public void insert(Chorro Chor)  throws PersistenciaException{
			String ins=null;
		
		try{
			QrysChorro cons = new QrysChorro();
			ins = cons.insertChorro();
			
			PreparedStatement pstmt1;
			DBC=new ConexionBD();
			
			pstmt1 = DBC.getConnection().prepareStatement(ins);
			pstmt1.setInt(1, Chor.getId());
			pstmt1.setInt(2, Chor.getIdPartida());
			if(Chor.isRoto())
				pstmt1.setInt(3, 1);
			else
				pstmt1.setInt(3, 0);
			
			pstmt1.executeUpdate();
			//cierro preparedStatement.
			pstmt1.close();
		}catch (SQLException e) {
			e.printStackTrace();
			throw new PersistenciaException("Se ha producido un error al intentar guardar el chorro");
		}finally{
			DBC.desconectar();
		}	
		
		}
		
		public ArrayList<Chorro> select(int idPart){
			String sel=null;
			ArrayList<Chorro>	 Chorros = new ArrayList<Chorro>();
			
			try{
				QrysChorro cons = new QrysChorro();
				Chorro Chor = new Chorro();
				sel = cons.selectChorro();
				
				PreparedStatement pstmt1;
				
				DBC=new ConexionBD();
				
				pstmt1 = DBC.getConnection().prepareStatement(sel);
				pstmt1.setInt(1, idPart);
				
				ResultSet rs = pstmt1.executeQuery();
				while(rs.next()){
					int id = rs.getInt("id");
					int roto = rs.getInt("roto");
					
					Chor.setId(id);
					Chor.setIdPartida(idPart);
					if(roto == 1)
						Chor.setRoto(true);
					else
						Chor.setRoto(false);
					
					Chorros.add(Chor);
				}
				rs.close();
				pstmt1.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
				throw new PersistenciaException("Se ha producido un error al intentar levantar chorros");
				}finally{
					DBC.desconectar();
					return Chorros;
					}	
				}
		}
		

